import fs from 'fs';
import path from 'path';
import { fileURLToPath, URL } from 'node:url';

import { defineConfig } from 'vite';
// import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import lightningcss from 'vite-plugin-lightningcss';
import { visualizer } from 'rollup-plugin-visualizer';
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
// https://vitejs.dev/config/
export default defineConfig((options) => {
  // 获取环境变量
  // const { mode } = options;
  // const root = process.cwd();
  // const env = loadEnv(mode, root);

  // 获取工程元数据
  const pkgPath = path.join(__dirname, './package.json');
  const pkgData = JSON.parse(fs.readFileSync(pkgPath) as any);
  const buildInfo = {
    'process.env.PROJECT_NAME': JSON.stringify(pkgData.name),
    'process.env.PROJECT_VERSION': JSON.stringify(pkgData.version),
    'process.env.APP_NAME': JSON.stringify(pkgData.appName),
    'process.env.PACKAGE_NAME': JSON.stringify(pkgData.packageName)
  };
  // 代理表
  const proxy = {
    // 大赢加CRM
    '^/proxyDyjApi': {
      // target: 'https://admin-roi.kaogujia.com',
      target: 'https://debug-admin-roi.kaogujia.com',
      changeOrigin: true,
      rewrite: (path: string) => path.replace(/^\/proxyDyjApi/, '')
    },
    // 创意
    '^/proxyCyApi': {
      target: 'http://material-admin.kaogujia.net',
      changeOrigin: true,
      rewrite: (path: string) => path.replace(/^\/proxyCyApi/, '')
    },
    // 考古加CRM
    '^/proxyApi': {
      target: 'http://test-crm-api.kaogujia.net',
      changeOrigin: true,
      rewrite: (path: string) => path.replace(/^\/proxyApi/, '')
    },
    // 分销
    '^/proxyAgencyApi': {
      target: 'https://roi.kaogujia.com/cms',
      changeOrigin: true,
      rewrite: (path: string) => path.replace(/^\/proxyAgencyApi/, '')
    },
    // 内容
    '^/proxyContentApi': {
      target: 'https://crm-api.kaogujia.com',
      changeOrigin: true,
      rewrite: (path: string) => path.replace(/^\/proxyContentApi/, '')
    }
  };

  // 插件
  const plugins = [
    vue(),
    vueJsx(),
    AutoImport({
      resolvers: [ElementPlusResolver()]
    }),
    Components({
      dirs: [], // 手动置空，避免src/components目录下的组件被自动解析
      resolvers: [ElementPlusResolver()]
    }),
    // 代替postcss
    lightningcss({
      browserslist: '>= 0.25%'
    }),
    createSvgIconsPlugin({
      iconDirs: [fileURLToPath(new URL('./src/assets/images/icons/svg', import.meta.url))],
      symbolId: 'icon-[dir]-[name]',
      svgoOptions: true
    })
  ];

  if (process.env.REPORT) {
    // 打包分析
    plugins.push(
      visualizer({
        open: true,
        gzipSize: true,
        filename: 'report.html',
        brotliSize: true
      })
    );
  }
  /** 解决optimized dependencies changed. reloading 导致页面刷新的问题 */
  const optimizeDepsElementPlusIncludes = ['element-plus/es'];
  fs.readdirSync('node_modules/element-plus/es/components').map((dirname) => {
    fs.access(`node_modules/element-plus/es/components/${dirname}/style/css.mjs`, (err) => {
      if (!err) {
        optimizeDepsElementPlusIncludes.push(`element-plus/es/components/${dirname}/style/css`);
      }
    });
  });
  const baseConfig = {
    plugins,
    server: {
      host: '0.0.0.0',
      open: true,
      port: '5173',
      proxy
    },
    define: buildInfo,
    optimizeDeps: {
      include: optimizeDepsElementPlusIncludes
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@use "@/assets/styles/scss/index.scss" as *;'
        }
      }
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url)),
        '@appGateway': fileURLToPath(new URL('./src/modules/app-gateway', import.meta.url)),
        '@crud': fileURLToPath(new URL('./src/modules/crud', import.meta.url)),
        '@auth': fileURLToPath(new URL('./src/modules/auth', import.meta.url)),
        '@images': fileURLToPath(new URL('./src/assets/images', import.meta.url))
        // '@package': fileURLToPath(
        //   new URL('../standard-project-pc-template/src/@package', import.meta.url)
        // )
      }
    },
    build: {
      esbuild: {
        drop: ['console', 'debugger']
      },
      sourcemap: false,
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks(id: string) {
            const independentChunks = ['element-plus', '@wangeditor'];
            const chunkVue = ['@vue', 'vue-router', 'pinia', '@vueuse', 'axios'];
            const chunkCharts = ['echarts', 'vue-echarts'];
            if (id.includes('node_modules')) {
              const moduleName = id.toString().split('node_modules/')[1].split('/')[0].toString();
              // if (chunkVue.includes(moduleName)) {
              //   return 'chunk-vue';
              // } else
              if (chunkCharts.includes(moduleName)) {
                return 'chunk-charts';
              } else if (independentChunks.includes(moduleName)) {
                return 'chunk-' + moduleName;
              } else {
                return 'vendor';
              }
            }
          }
        }
      }
    }
  };

  return baseConfig;
});
